<template>
  <div>
    <div
      style="position: absolute;width:260px;height:30px;top:86px;left: calc(100vw - 260px);z-index: 999"
    >
      <el-dropdown style="display: inline">
        <el-link
          style="font-size: 14px;float: left;line-height: 30px;margin-right: 5px;"
          type="success"
        >排队数量: {{ queueInfo.allNum }}</el-link>
        <template slot="dropdown">
          <el-dropdown-item
            v-for="chatType in queueInfo.chatTypes"
            :key="chatType.typeName"
          >{{ chatType.typeName }} : {{ chatType.waitingNum }}</el-dropdown-item>
        </template>
      </el-dropdown>
      <el-button-group style="display: inline">
        <el-button type="primary" v-if="!state.signIn" @click="this.signIn">签入</el-button>
        <el-button type="primary" v-if="state.signIn" @click="this.signOut">签出</el-button>
        <el-button type="primary" @click="this.ready" :disabled="!state.ready">就绪</el-button>
        <el-button type="primary" @click="this.rest" :disabled="!state.rest">小休</el-button>
      </el-button-group>
    </div>
    <el-row>
      <el-col :span="24">
        <el-tabs
          type="border-card"
          closable
          @tab-remove="this.tabRemove"
          @tab-click="this.tabClick"
          v-model="currentChat.clientName"
          class="demo-tabs"
        >
          <el-tab-pane v-for="chat in this.chats" :key="chat.id" :name="chat.clientName">
            <template slot="label">
              <span class="custom-tabs-label">
                <span>{{ chat.clientName }}</span>
                <el-badge
                  v-if="chat.unreadCount > 0"
                  class="mark"
                  style="margin-left:5px"
                  :value="chat.unreadCount"
                />
              </span>
            </template>
            <el-row>
              <el-col :span="12">
                <div>
                  <!-- 消息框 -->
                  <div
                    ref="msgBoxs"
                    :title="chat.id"
                    style="height:calc(100vh - 340px); overflow:auto; border: 1px solid #ccc;
                          border-radius: 5px;background-color: #f5f5f5;"
                  >
                    <!-- <messages :msgs="chat.msgs" show-at="agent"></messages> -->
                  </div>
                  <!-- 消息框结束 -->
                  <div
                    style="display: flex;align-items:center;height:20px;border:none;margin: 0 15px"
                  >
                    <div>
                      <el-upload
                        ref="uploadRef"
                        class="upload-demo"
                        action="/api/common/upload/imgMsg"
                        :show-file-list="false"
                        :before-upload="this.beforeUpload"
                        :on-success="this.onSuccess"
                        :on-error="this.onError"
                      >
                        <template slot="trigger">
                          <el-tooltip
                            class="box-item"
                            effect="light"
                            content="发送图片"
                            placement="top"
                          >
                            <el-icon title>
                              <picture></picture>
                            </el-icon>
                          </el-tooltip>
                        </template>
                      </el-upload>
                    </div>
                    <div>
                      <el-tooltip
                        class="box-item"
                        effect="light"
                        :content="audioTitle"
                        placement="top"
                      >
                        <el-icon
                          style="margin: 0 15px"
                          @mousedown="this.startRecordAudio"
                          @mouseup="this.endRecordAudio"
                        >
                          <microphone></microphone>
                        </el-icon>
                      </el-tooltip>
                    </div>
                    <div>
                      <el-switch
                        v-model="reverseRecord"
                        class="ml-2"
                        width="60"
                        size="small"
                        inline-prompt
                        active-text="反转"
                        inactive-text="正常"
                      />
                    </div>
                  </div>
                  <!-- 输入框 -->
                  <div
                    style="height: 120px;border-radius: 5px;border:1px solid #ccc;"
                    v-show="chat.alive"
                  >
                    <textarea
                      @keydown.enter.prevent="this.send(chat)"
                      style="height: 100%; width: 100%; padding-top: 10px;
                               outline: none;border: none; resize: none"
                      v-model="chat.inputBox"
                    ></textarea>
                    <el-button
                      style="margin-top:10px;float:right"
                      type="primary"
                      @click="this.send(chat)"
                    >发送</el-button>
                  </div>
                  <!-- 输入框结束 -->
                </div>
              </el-col>
              <el-col :span="12" style="padding:0 5px">
                <el-tabs style="height: 100%" type="border-card">
                  <el-tab-pane label="服务单">
                    <!-- <ServiceTicket :chat-id="chat.id" :client-id="chat.clientId" type="edit"></ServiceTicket> -->
                  </el-tab-pane>
                  <el-tab-pane
                    label="历史记录"
                    class="scrollDiv"
                    style="height:calc(100vh - 240px);overflow-y: scroll"
                  >
                    <!-- <chat :client-id="chat.clientId"></chat> -->
                  </el-tab-pane>
                </el-tabs>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <el-dialog v-model="closeConfirm" title="确认" width="30%">
      <span>确认关闭和{{ currentChat.clientName }}的会话?</span>
      <template slot="footer">
        <span class="dialog-footer">
          <el-button @click="closeConfirm = false">取消</el-button>
          <el-button type="primary" @click="this.closeChat">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- <record-audio ref="recordAudio"></record-audio> -->
  </div>
</template>

<script>
import ServiceTicket from './restFile/ServiceTicket.vue';
// import Messages from "./Messages.vue";
// import RecordAudio from "../aMessage/RecordAudio.vue";
// import Chat from "@/views/business/Chat.vue";
// import moment from "moment";
// import request from "@/components/bus/request";
// import Recorder from "js-audio-recorder";
export default {
  name: "AgentInterface",
  components: {
    ServiceTicket,
    // Messages,
    // RecordAudio,
    // Chat
  },
  data() {
    return {
      currentChat: { clientName: null },
      msgBoxs: [],
      chats: [],
      websocket: null,
      msgMap: new Map(),
      agentId: null,
      connect: false,
      closeConfirm: false,
      recordAudio: null,
      reverseRecord: false,
      waitForClose: null,
      queueInfo: { allNum: 0, chatTypes: [] },
      state: { signIn: false, ready: false, rest: false },
      recorder: null,
      audioTitle: "发送语音"
    };
  },
  created() {
    this.initWebSocket();
    this.recorder = new Recorder({
      sampleBits: 16,
      numChannels: 1,
      compiling: false
    });
  },
//   mounted() {
//     let userdb = JSON.parse(sessionStorage.getItem("user") || "{}");
//     this.agentId = userdb.id;
//     let host = window.location.host;
//     this.websocket = new WebSocket(
//       `ws://${host}/socket/agent/` + userdb.id + "/0"
//     );

//     this.websocket.onerror = e => {
//       this.$message.error("websocket连接出错");
//     };
//     this.websocket.onopen = () => {
//       this.connect = true;
//     };
//     this.websocket.onmessage = event => {
//       console.log(event.data);
//       let msg = JSON.parse(event.data);

//       if ("queue" == msg.type) {
//         let queueInfos = JSON.parse(msg.content);
//         makeQueueInfo(queueInfos);
//         return;
//       }

//       let chat = null;
//       let index = null;
//       for (let i = 0; i < chats.length; i++) {
//         if (chats[i].id == msg.chatId) {
//           chat = chats[i];
//           index = i;
//           break;
//         }
//       }
//       if ("close" == msg.type && "agent" == msg.sender) {
//         chats.splice(index);
//         closeConfirm.value = false;
//         return;
//       }
//       if ("close" == msg.type && "client" == msg.sender) {
//         chat.alive = false;
//         return;
//       }
//       if (chat == null) {
//         chat = {
//           id: msg.chatId,
//           clientName: msg.senderName,
//           clientId: msg.senderId,
//           unreadCount: 1,
//           alive: true,
//           msgs: [msg]
//         };
//         chats.push(chat);
//       } else {
//         chat.msgs.push(msg);
//         if (msg.sender != "agent") {
//           if (currentChat.id != chat.id) {
//             chat.unreadCount++;
//           }
//         }
//       }
//       if (
//         currentChat.clientName == null ||
//         currentChat.clientName == msg.senderName
//       ) {
//         // 消息来自当前聊天的客户
//         for (let key in chat) {
//           currentChat[key] = chat[key];
//         }
//       }

//       if ("client" === msg.sender) {
//         if (chats.length == 1) {
//           currentChat.clientName = msg.senderName;
//           chat.unreadCount = 0;
//         }
//       }
//       scrollerToBottom(chat.id);
//     };
//     this.keepalive = setInterval(() => {
//       // ... your logic here ...
//     }, 30 * 1000);
//   },
//   beforeDestroy() {
//     if (this.websocket) {
//       this.websocket.close();
//     }
//     clearInterval(this.keepalive);
//   },
//   methods: {
//     send(chat) {
//       let content = chat.inputBox.trim();
//       if (content === "") {
//         ElMessage({ message: "请输入内容", type: "error" });
//         return;
//       }
//       let msg = {
//         content: content,
//         type: "text",
//         chatId: chat.id,
//         senderName: currentChat.senderName
//       };
//       websocket.send(JSON.stringify(msg));
//       chat.inputBox = "";
//     },
//     tabRemove(clientName) {
//       closeConfirm.value = true;
//       for (let i = 0; i < chats.length; i++) {
//         if (chats[i].clientName == clientName) {
//           waitForClose = chats[i];
//           break;
//         }
//       }
//     },
//     closeChat() {
//       let msg = {
//         type: "close",
//         chatId: this.waitForClose.id,
//         senderName: this.waitForClose.senderName
//       };
//       this.websocket.send(JSON.stringify(msg));
//     },

//     tabClick(tab, event) {
//       let chat = null;
//       this.currentChat.clientName = tab.props.name;
//       for (let i = 0; i < this.chats.length; i++) {
//         if (this.chats[i].clientName === tab.props.name) {
//           chat = this.chats[i];
//           Object.assign(this.currentChat, chat);
//           break;
//         }
//       }
//       chat.unreadCount = 0;
//     },

//     scrollerToBottom(chatId) {
//       let areas = this.$refs.msgBoxs;
//       let thisArea = null;
//       for (let i = 0; i < areas.length; i++) {
//         let temp = areas[i];
//         if (temp.title === chatId) {
//           thisArea = temp;
//           break;
//         }
//       }
//       this.$nextTick(() => {
//         if (thisArea !== null) {
//           thisArea.scrollTop = thisArea.scrollHeight;
//         }
//       });
//     },

//     makeQueueInfo(queueInfos) {
//       let allNum = 0;
//       this.queueInfo.chatTypes = [];
//       queueInfos.forEach(info => {
//         this.queueInfo.chatTypes.push({
//           typeName: info.typeName,
//           waitingNum: info.waitingNum
//         });
//         allNum += info.waitingNum;
//       });
//       this.queueInfo.allNum = allNum;
//     },

//     signIn: function() {
//       if (!this.connect) {
//         this.$message.error("请等待连接成功");
//       }
//       request.get(`/api/online/signIn/${this.agentId}`).then(resp => {
//         this.state.signIn = true;
//         this.state.ready = true;
//         this.state.rest = false;
//       });
//     },

//     signOut() {
//       if (!this.connect) {
//         this.$message.error("请等待连接成功");
//       }
//       request.get(`/api/online/signOut/${this.agentId}`).then(resp => {
//         this.state.ready = false;
//         this.state.rest = false;
//         this.state.signIn = false;
//       });
//     },

//     ready() {
//       if (!this.connect) {
//         this.$message.error("请等待连接成功");
//       }
//       request.get(`/api/online/ready/${this.agentId}`).then(resp => {
//         this.state.ready = false;
//         this.state.rest = true;
//       });
//     },

//     rest() {
//       if (!this.connect) {
//         this.$message.error("请等待连接成功");
//       }
//       request.get(`/api/online/rest/${this.agentId}`).then(resp => {
//         this.state.ready = true;
//         this.state.rest = false;
//       });
//     },
//     beforeUpload(rawFile) {
//       console.log("文件格式：" + rawFile.type);
//       if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
//         this.$message.error("必须是 JPG或PNG 格式!");
//         return false;
//       } else if (rawFile.size / 1024 / 1024 > 2) {
//         this.$message.error("文件大小不能大于2MB!");
//         return false;
//       }
//       return true;
//     },
//     onSuccess(response, uploadFile, uploadFiles, chat) {
//       this.$message.success("发送图片成功!");
//       let msg = {
//         content: response.data,
//         type: "image",
//         chatId: this.currentChat.id,
//         senderName: this.currentChat.senderName
//       };
//       let realMsg = JSON.stringify(msg);
//       this.websocket.send(realMsg);
//     },
//     onError(error, uploadFile, uploadFiles) {
//       this.$message.error("发送图片失败" + error);
//     },
//     startRecordAudio() {
//       this.$message({ message: "开始录音", type: "success", duration: 700 });
//       this.audioTitle = "正在录制。。。";
//       Recorder.getPermission().then(
//         () => {
//           this.recorder.start(); // 开始录音
//         },
//         error => {
//           this.$message({
//             message: "请先允许该网页使用麦克风",
//             type: "error",
//             duration: 700
//           });
//         }
//       );
//     },
//     endRecordAudio() {
//       this.$message({ message: "录音结束", type: "success", duration: 700 });
//       this.audioTitle = "发送语音";
//       this.recorder.stop(); // 结束录音
//       let wavBlob = this.recorder.getWAVBlob();
//       let formData = new FormData();
//       const newbolb = new Blob([wavBlob], { type: "audio/wav" });
//       const fileOfBlob = new File([newbolb], new Date().getTime() + ".wav");
//       formData.append("file", fileOfBlob);
//       const config = {
//         headers: {
//           "Content-Type": "multipart/form-data;boundary=" + new Date().getTime()
//         }
//       };
//       let url = "/api/common/upload/audio";
//       if (this.reverseRecord) {
//         url = "/api/online/reverseRecord";
//       }
//       request.post(url, formData, config).then(resp => {
//         let msg = {
//           content: resp,
//           type: "audio",
//           chatId: this.currentChat.id,
//           senderName: this.currentChat.senderName
//         };
//         let realMsg = JSON.stringify(msg);
//         this.websocket.send(realMsg);
//       });
//     }

//     // ... other methods ...
//   }
};
</script>

<style scoped>
.tip {
  border-radius: 10px;
  padding: 10px;
  width: auto;
  display: inline-block;
  word-wrap: break-word;
  word-break: break-all;
  text-align: left;
  max-width: 60%;
}
.time {
  padding: 5px;
  display: inline-block;
  color: #8f9093;
  font-size: 13px;
}
.item {
  margin-top: 5px;
}
.right {
  background-color: #84db49;
}
.left {
  background-color: white;
}
.span-box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.btn-bell-badge {
  width: 26px;
  height: 18px;
  margin-left: 5px;
  line-height: 18px;
  border-radius: 15px;
  background: #f56c6c;
}
.num {
  display: block;
  width: 100%;
  text-align: center;
  font-size: 12px;
  color: #fff;
}
</style>